<?php
/**
 *  消息处理    
 *  author： 王朝忠 
 *  date  ： 2017-12-08
 */
namespace Admin\Controller;
class MessageController extends AbstractController  {

    function _initialize() {
        parent::_initialize();
    }

    //发送者（管理者）消息列表 权限待做
    public function index(){
        $keyword = I('post.keyword/s');
        if(!empty($keyword)){
            $where['a.Title|b.UserName|b.TrueName'] = array('like','%'.$keyword.'%');
        }
        $where['a.SUID'] = session('ADMIN_ID');
        $count  = M('Message')->alias('a')
        ->join('user b on a.SUID=b.ID')
        ->where($where)
        ->count();
        $page = $this->page($count, 20);    
        $Messages = M('Message')
        ->alias('a')
        ->field('a.*,b.UserName,b.TrueName')
        ->join('user b on a.SUID=b.ID')
        ->where($where)
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        $this->assign("page", $page->show('Admin'));
        $this->assign("Messages",$Messages);
        $this->display(); 
    }

    //个人消息列表
    public function my_messages(){
        $keyword = I('post.keyword/s');
        if(!empty($keyword)){
            $where['a.Title'] = array('like','%'.$keyword.'%');
        }
        $where['c.GUID'] = session('ADMIN_ID');
        $count  = M('Message')
        ->alias('a')
        ->join('user b on a.SUID=b.ID')
        ->join('message_user_rel c on a.ID=c.MID')
        ->where($where)
        ->count();
        $page = $this->page($count, 20);    
        $Messages = M('Message')
        ->alias('a')
        ->field('a.*,b.UserName,b.TrueName,c.OpenTime')
        ->join('user b on a.SUID=b.ID')
        ->join('message_user_rel c on a.ID=c.MID')
        ->where($where)
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        $this->assign("page", $page->show('Admin'));
        $this->assign("Messages",$Messages);
        $this->display(); 
    }

    //消息详情。发送者（管理者）权限待做
    public function show(){
        $ID = I('get.id');
        $msg = M('Message')
        ->alias('a')
        ->field('a.*,b.UserName,b.TrueName')
        ->join('user b on a.SUID=b.ID')
        ->where(array('a.ID'=>$ID))
        ->find();
        $msg_users = M('message_user_rel')
       ->alias('a')
       ->field('a.OpenTime,b.ID,b.UserName,b.TrueName')
       ->join('user b on a.GUID=b.ID')
       ->where(array('a.MID'=>$msg['ID']))
       ->select();
        $this->assign("msg_users",$msg_users);
        $this->assign("msg",$msg);
        $this->display();   
    }

    //消息详情
    public function detail(){
        $ID = I('get.id');
        $msg = M('Message')
        ->alias('a')
        ->field('a.*,b.UserName,b.TrueName')
        ->join('user b on a.SUID=b.ID')
        ->join('message_user_rel c on a.ID=c.MID')
        ->where(array('a.ID'=>$ID,'c.GUID'=>session('ADMIN_ID')))
        ->find();
        $this->assign("msg",$msg);
        M('message_user_rel')->where(array('MID'=>$ID,'GUID'=>session('ADMIN_ID')))->save(array('OpenTime'=>date('Y-m-d H:i:s')));//已阅读
        $this->display();   
    }

    //发送消息
    public function send(){
        $this->display('send');
    }
    
    //消息发送提交
    public function send_post(){
        if(IS_POST){
            $rtn = array("code"=>-1,"notice"=>"");
            $data = $_POST;
            $GUID = $_POST['GUID'];
            if(empty($GUID)){
                $rtn['notice'] = "接收用户未选择！";
                $this->ajaxReturn($rtn); 
            }
            $Content = $_POST['Content'];
            $title = $_POST['Title'];
            $res = send_messag(implode(',',$GUID),$title,$Content);
            if($res){
                $rtn['code'] = 0;//返回成功
            }else{
                $rtn['notice'] = "失败！";
            }
            $this->ajaxReturn($rtn);
            // $MessageModel = D("Message");
            // $data['SUID']  = session('ADMIN_ID');
            // $data['SendTime']  = date('Y-m-d H:i:s');
            // $data['Content'] = htmlspecialchars_decode($_POST['Content']);
            // unset($data['GUID']);
            // $result = $MessageModel->add($data);
            // if($result){
            //     $data = array();
            //     if($GUID[0]=='all'){
            //        $GUID = $this->getUsers();
            //     }
            //     foreach ($GUID as $key => $val) {
            //         $data['GUID'] = $val;
            //         $data['MID'] = $result;
            //         $data['OpenTime'] = null;
            //         M('message_user_rel')->add($data);
            //     }

            //     $rtn['code'] = 0;//返回成功
            // }else{
            //     $rtn['notice'] = "添加失败！";
            // }
            //$this->ajaxReturn($rtn);
        }
    }

    //内容预处理
    public function up_msg_img_content(){
        if($_FILES){
            $rtn = "";
            $config = array(
                'maxSize' => 5*1024*1024,
                'rootPath' => './data/upload/message/content/',
                'savePath' => '',
                'saveName' => array('uniqid',''),
                'exts' => array('jpg', 'gif', 'png', 'jpeg'),
                'autoSub' => true,
                'subName' => array('date','Ymd')
            );
            createdirlist($config['rootPath']);
            $upload = new \Think\Upload($config);// 实例化上传类
            // 上传文件
            $info = $upload->upload($_FILES);
            if(!$info) {// 上传错误提示错误信息
                $rtn = $this->error($upload->getError());
            }else{// 上传成功
                foreach ($info as $key=>$img){
                    if($key==0){
                        $rtn .= $config['rootPath'].$img['savepath'].$img['savename'];
                    }else{
                        $rtn .= "|".$config['rootPath'].$img['savepath'].$img['savename'];
                    }
                }
            }
            echo $rtn;
            die;
        }
    }
    
    //删除
    public function delete(){
        $ID = I('get.id');
        $MessageModel=M("Message");
        $result = $MessageModel->where(array('ID'=>$ID))->delete();
        if ($result!==false) {
            M('message_user_rel')->where(array('MID'=>$ID))->delete();
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        } 
    }

    public function chosen_user(){
        $keyword = I('request.keyword');
        $where = '';
        if(!empty($keyword)){ 
           $where = ' and (a.UserName like "%'.$keyword.'%" or a.TrueName like "%'.$keyword.'%")';  
        }   
        $sql = 'select a.ID,a.TrueName,a.UserName from user a  where a.IsDel=0 and a.ID != 1 '.$where.' group by a.ID' ;        
        $lists = M()->query($sql);
        $this->ajaxReturn(array('datas'=>$lists,'status'=>'success'),'JSON');
    }
}